<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let idCard = '40012319220530344X'
    // 正则里面加 () 表示分组
    let reg = /^(\w{6})(\w{8})(\w{4})$/

    // console.log(reg.exec(idCard)[3]);

    // const res = idCard.replace(reg, (...args) => {
    //   // console.log(args);
    //   return args[1] + '*'.repeat(8) + args[3]
    // })
    // console.log(res)

    const res = idCard.replace(reg, '$1********$2')
    console.log(res)

  </script>
</body>

</html>